package com.imut.lagain.interceptor;

import com.imut.lagain.config.PerformanceMonitorProperties;
import com.imut.lagain.service.PerformanceMonitorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 性能监控拦截器
 * 用于监控API调用性能
 */
@Component
public class PerformanceInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(PerformanceInterceptor.class);
    
    private final PerformanceMonitorService performanceMonitorService;
    private final PerformanceMonitorProperties properties;
    
    private static final String START_TIME_ATTRIBUTE = "performanceStartTime";
    
    public PerformanceInterceptor(PerformanceMonitorService performanceMonitorService, 
                                PerformanceMonitorProperties properties) {
        this.performanceMonitorService = performanceMonitorService;
        this.properties = properties;
    }
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (properties.isEnabled()) {
            request.setAttribute(START_TIME_ATTRIBUTE, System.currentTimeMillis());
        }
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
                              Object handler, Exception ex) {
        if (!properties.isEnabled()) {
            return;
        }
        
        Long startTime = (Long) request.getAttribute(START_TIME_ATTRIBUTE);
        if (startTime != null) {
            long duration = System.currentTimeMillis() - startTime;
            String endpoint = request.getMethod() + " " + request.getRequestURI();
            boolean success = response.getStatus() < 400 && ex == null;
            
            // 根据采样率决定是否记录
            if (Math.random() <= properties.getSamplingRate()) {
                performanceMonitorService.recordApiCall(endpoint, duration, success);
                
                // 记录慢API
                if (duration > properties.getApiSlowThreshold()) {
                    log.warn("Slow API detected: {} took {}ms", endpoint, duration);
                }
            }
        }
    }
}